import { Body, Controller, Get, Post, UseInterceptors } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import { AdminService } from "./admin.service";
import { WebResult } from "src/common/web.result";
import { AdminLoginInterceptor } from "src/admin/interceptor/alogin.interceptor";
import { UserTokenService } from "src/user/token.service";
import { UserService } from "src/user/user.service";
import { UserLoginDTO } from "src/user/dto/user-login.dto";

@Controller("admin")
export class AdminController {
  constructor(
    private readonly prisma: PrismaClient,
    private readonly userTokenService: UserTokenService,
    private readonly userService: UserService,
    private readonly adminService: AdminService,
  ) {}

  @Get("/verifyToken")
  @UseInterceptors(AdminLoginInterceptor)
  verifyToken() {
    return WebResult.success(true);
  }

  @Post("/login")
  async login(@Body() userLoginDTO: UserLoginDTO) {
    const user = await this.prisma.user.findUnique({
      select: {
        id: true,
        password: true,
      },
      where: {
        username: userLoginDTO.username,
      },
    });
    if (!user) return WebResult.failure(undefined, "用户不存在");

    if (userLoginDTO.password !== user.password) {
      return WebResult.failure(undefined, "密码错误");
    }
    if (!this.userService.isAdministrator(userLoginDTO.username)) {
      return WebResult.failure(undefined, "用户无权限");
    }
    const token = this.userTokenService.generateToken({
      userID: user.id,
      username: userLoginDTO.username,
      password: user.password,
    });
    return WebResult.success(token, "登录成功");
  }
}
